<template>
  <div class="app-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <p class="page-subtitle">管理系统用户信息，包括用户标签、积分、会员等功能</p>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <el-row :gutter="16" class="mb16">
        <el-col :span="2">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            class="action-btn"
          >新增用户</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card class="search-card" shadow="never">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
          <el-form-item label="搜索类型">
            <el-select v-model="searchType" placeholder="请选择搜索类型" class="search-select">
              <el-option label="用户姓名" value="username"></el-option>
              <el-option label="手机号" value="phone"></el-option>
              <el-option label="真实姓名" value="realName"></el-option>
              <el-option label="用户账号" value="accountNumber"></el-option>
              <el-option label="会员卡号" value="memberNumber"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="搜索内容">
            <el-input
              v-model="searchValue"
              placeholder="请输入搜索内容"
              clearable
              @keyup.enter="handleQuery"
              class="search-input"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery" class="search-btn">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery" class="reset-btn">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 批量操作区域 -->
    <div class="batch-section">
      <el-card class="batch-card" shadow="never">
        <div class="batch-header">
          <span class="batch-title">批量操作</span>
          <span class="batch-tip">请先选择用户，然后进行批量操作</span>
        </div>
        <el-row :gutter="12" class="batch-buttons">
          <el-col :span="3">
            <el-button
              type="primary"
              plain
              :disabled="multiple"
              @click="handleOpenTagDialog"
              class="batch-btn"
            >
              <el-icon><User /></el-icon>
              设置用户标签
            </el-button>
          </el-col>
          <el-col :span="3">
            <el-button
              type="success"
              plain
              :disabled="multiple"
              @click="openPointsDialog = true"
              class="batch-btn"
            >
              <el-icon><User /></el-icon>
              修改积分
            </el-button>
          </el-col>
          <el-col :span="3">
            <el-button
              type="warning"
              plain
              :disabled="multiple"
              @click="handleSendCoupon"
              class="batch-btn"
            >
              <el-icon><User /></el-icon>
              送优惠券
            </el-button>
          </el-col>
          <el-col :span="3">
            <el-button
              type="info"
              plain
              :disabled="multiple"
              @click="openMemberDialog = true"
              class="batch-btn"
            >
              <el-icon><User /></el-icon>
              开通会员
            </el-button>
          </el-col>
          <el-col :span="3">
            <el-button
              type="success"
              plain
              :disabled="multiple"
              @click="openSetMemberDialog"
              class="batch-btn"
            >
              <el-icon><User /></el-icon>
              设置会员
            </el-button>
          </el-col>
          <el-col :span="3">
            <el-button
              type="danger"
              plain
              :disabled="multiple"
              @click="handleExport"
              class="batch-btn"
            >
              <el-icon><User /></el-icon>
              冻结用户
            </el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 用户列表区域 -->
    <div class="table-section">
      <el-card class="table-card" shadow="never">
        <el-table 
          v-loading="loading" 
          :data="userList" 
          @selection-change="handleSelectionChange" 
          class="user-table"
          stripe
          border
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="ID" align="center" prop="id" width="80" />
          <el-table-column label="用户信息" align="center" width="180">
            <template #default="scope">
              <div class="user-info-container">
                <div class="user-avatar">
                  <el-avatar :size="50" :src="scope.row.photo">
                    <el-icon><User /></el-icon>
                  </el-avatar>
                </div>
                <div class="user-info">
                                      <div class="user-name">{{ scope.row.username }}</div>
                    <div class="user-phone">{{ scope.row.phone }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
          <el-table-column label="用户账号" align="center" prop="accountNumber" width="120"/>
          <el-table-column label="真实姓名" align="center" prop="realName" width="100" />
          <el-table-column label="来源渠道" align="center" prop="sourceName" width="120" />
          <el-table-column label="会员账号" align="center" prop="memberNumber" width="120"/>
          <el-table-column label="会员名称" align="center" prop="memberName" width="120" />
          <el-table-column label="加入时间" align="center" prop="createTime" width="160"/>
          <!-- <el-table-column label="最近消费时间" align="center" prop="lastConsumeTime" width="140" />
          <el-table-column label="消费金额" align="center" prop="lastConsumeAmount" width="100" />
          <el-table-column label="累计消费次数" align="center" prop="totalConsumeCount" width="120" />
          <el-table-column label="消费总金额" align="center" prop="totalConsumeAmount" width="120" /> -->
          <el-table-column label="用户标签" align="center" width="200" min-width="200">
            <template #default="scope">
              <div class="user-tags-list">
                <el-tag
                  v-for="tag in (scope.row.userTags || [])"
                  :key="tag.tagId"
                  type="info"
                  size="small"
                  class="user-tag"
                >
                  {{ tag.tagName }}
                </el-tag>
                <span v-if="!scope.row.userTags || scope.row.userTags.length === 0" class="no-tags">
                  暂无标签
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
            <template #default="scope">
              <el-button link type="primary" @click="handleDetails(scope.row)" class="action-link">
                <el-icon><User /></el-icon>
                详情
              </el-button>
              <el-button link type="warning" @click="handleFreeze(scope.row)" class="action-link">
                <el-icon><User /></el-icon>
                冻结
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <pagination
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </el-card>
    </div>

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body class="user-dialog" :key="dialogKey">
      <el-form ref="userRef" :model="form" :rules="rules" label-width="120px">
        <!-- 用户基本信息区域 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><User /></el-icon>
            <span>基本信息</span>
          </div>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="用户姓名" prop="username" required>
                <el-input v-model="form.username" placeholder="请输入用户姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="真实姓名" prop="realName">
                <el-input v-model="form.realName" placeholder="请输入真实姓名" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="密码" prop="password" required>
                <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone" required>
                <el-input v-model="form.phone" placeholder="请输入手机号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="来源渠道" prop="sourceId" required>
                <el-select v-model="form.sourceId" placeholder="请选择来源渠道" style="width: 100%">
                  <el-option v-for="item in sourceList" :key="item.id" :label="item.sourceName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 头像上传区域 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><User /></el-icon>
            <span>头像设置</span>
          </div>
          <el-form-item label="头像" prop="photo">
            <div class="avatar-upload-container">
              <image-upload v-model="form.photo"/>
              <div class="upload-tips">
                <p>请上传大小不超过5MB，格式为 png/jpg/jpeg 的文件</p>
                <p class="highlight">支持格式：PNG、JPG、JPEG</p>
                <p class="highlight">文件大小：≤ 5MB</p>
              </div>
            </div>
          </el-form-item>
        </div>

        <!-- 个人信息区域 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><User /></el-icon>
            <span>个人信息</span>
          </div>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="性别" prop="sex" required>
                <el-radio-group v-model="form.sex" class="gender-group">
                  <el-radio label="1" class="gender-radio">
                    <el-icon><User /></el-icon>
                    男
                  </el-radio>
                  <el-radio label="2" class="gender-radio">
                    <el-icon><User /></el-icon>
                    女
                  </el-radio>
                  <el-radio label="3" class="gender-radio">
                    <el-icon><User /></el-icon>
                    未知
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年龄" prop="age" required>
                <el-input v-model="form.age" placeholder="请输入年龄" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="生日" prop="birthTime">
                <el-date-picker 
                  clearable
                  v-model="form.birthTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择生日"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>



        <!-- 用户标签区域 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><User /></el-icon>
            <span>用户标签</span>
          </div>
          <el-form-item label="用户标签" prop="userTags">
            <div class="user-tags-container">
              <el-tag
                v-for="tag in userTags"
                :key="tag.tagId"
                type="info"
                class="form-tag"
                closable
              >
                {{ tag.tagName }}
              </el-tag>
              <span v-if="userTags.length === 0" class="no-tags">暂无标签</span>
            </div>
          </el-form-item>
        </div>

        <!-- 收货地址区域 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><User /></el-icon>
            <span>收货地址</span>
          </div>
          <div v-if="shippingAddress && shippingAddress.length > 0" class="shipping-address-container">
            <div v-for="(address, index) in shippingAddress" :key="index" class="address-item">
              <div class="address-header">
                <span class="address-title">
                  收货地址 {{ index + 1 }}
                  <el-tag v-if="address.isDefault" type="success" size="small" class="default-tag">默认地址</el-tag>
                </span>
              </div>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="收货人">
                    <el-input v-model="address.recipient" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="收货人手机号码">
                    <el-input v-model="address.recipientPhone" readonly />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="8">
                  <el-form-item label="省份">
                    <el-input v-model="address.provinceName" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="城市">
                    <el-input v-model="address.cityName" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="区县">
                    <el-input v-model="address.districtName" readonly />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="详细地址">
                <el-input v-model="address.detailAddress" type="textarea" readonly :rows="2" />
              </el-form-item>
            </div>
          </div>
          <div v-else class="no-address-container">
            <el-empty description="暂无收货地址信息" />
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 开通会员对话框 -->
    <el-dialog title="设置会员等级" v-model="openMemberDialog" width="700px" append-to-body class="member-dialog">
      <el-table :data="memberList" style="width: 100%" stripe>
        <el-table-column label="选择" width="80" align="center">
          <template #default="scope">
            <el-radio :label="scope.row.id" v-model="memberId"></el-radio>
          </template>
        </el-table-column>
        <el-table-column label="会员名称" prop="memberName" width="180" />
        <el-table-column label="会员方式" prop="memberWay" width="180" />
        <el-table-column label="会员有效期" prop="memberValidity" width="180" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openMemberDialog = false">取消</el-button>
          <el-button type="primary" @click="submitMember">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设置用户标签对话框 -->
    <el-dialog title="设置用户标签" v-model="openTagDialog" width="700px" append-to-body class="tag-dialog">
      <div class="tag-search-container">
        <el-input
          v-model="tagSearchValue"
          placeholder="请输入标签关键词"
          prefix-icon="Search"
          clearable
          @input="filterTags"
          class="tag-search-input"
        />
      </div>
      <div class="tag-list-container">
        <el-checkbox-group v-model="selectedTagIds" class="tag-checkbox-group">
          <el-checkbox
            v-for="tag in filteredTags"
            :key="tag.tagId"
            :label="tag.tagId"
            class="tag-checkbox"
          >
            {{ tag.tagName }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <div class="selected-tags-info">
        已选择 {{ selectedTagIds.length }} 个标签
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openTagDialog = false">取消</el-button>
          <el-button type="primary" @click="submitTags">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改积分对话框 -->
    <el-dialog title="修改积分" v-model="openPointsDialog" width="500px" append-to-body class="points-dialog">
      <el-form ref="pointsFormRef" :model="pointsForm" :rules="pointsRules" label-width="100px">
        <el-form-item label="修改积分" prop="integral">
          <el-input v-model="pointsForm.integral" placeholder="请输入积分" />
          <div class="form-tips">输入100，表示增加100，输入-100，表示减少100</div>
        </el-form-item>
        <el-form-item label="修改原因" prop="modifyReason">
          <el-input v-model="pointsForm.modifyReason" type="textarea" placeholder="请输入修改原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openPointsDialog = false">取消</el-button>
          <el-button type="primary" @click="submitPointsForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 优惠券选择对话框 -->
    <el-dialog
      v-model="couponDialogVisible"
      title="选择优惠券"
      width="900px"
      :before-close="handleCloseCouponDialog"
    >
      <div class="coupon-container">
        <!-- 选中用户信息 -->
        <div class="selected-users-info">
          <h4>已选用户 ({{ selectedUsers.length }}人)</h4>
          <div class="users-list">
            <el-tag
              v-for="user in selectedUsers"
              :key="user.id"
              type="info"
              closable
              @close="removeSelectedUser(user)"
              class="user-tag"
            >
              {{ user.username }} - {{ user.realName || '未设置姓名' }}
            </el-tag>
          </div>
        </div>

        <!-- 优惠券列表 -->
        <div class="coupon-list-section">
          <h4>选择优惠券</h4>
          <p class="coupon-tip">请从下方表格中选择要发送的优惠券，选择后可在下方设置每个优惠券的发放数量</p>
          <el-table 
            :data="couponList" 
            style="width: 100%" 
            stripe
            @selection-change="handleCouponSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="优惠券名称" prop="name" width="200" />
            <el-table-column label="类型" prop="type" width="100">
              <template #default="scope">
                <el-tag v-if="scope.row.type === 1" type="success">满减券</el-tag>
                <el-tag v-else-if="scope.row.type === 2" type="warning">折扣券</el-tag>
                <el-tag v-else-if="scope.row.type === 3" type="primary">通用券</el-tag>
                <el-tag v-else type="info">其他</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="面值" prop="faceValue" width="120">
              <template #default="scope">
                <span v-if="scope.row.type === 1">¥{{ scope.row.faceValue }}</span>
                <span v-else-if="scope.row.type === 2">{{ scope.row.faceValue }}折</span>
                <span v-else>¥{{ scope.row.faceValue }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库存数量" prop="totalQuantity" width="120">
              <template #default="scope">
                <span>{{ scope.row.totalQuantity || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="最低消费" prop="minOrderAmount" width="120">
              <template #default="scope">
                <span v-if="scope.row.minOrderAmount > 0">¥{{ scope.row.minOrderAmount }}</span>
                <span v-else class="no-limit">无限制</span>
              </template>
            </el-table-column>
            <el-table-column label="有效期" prop="expireTime" width="180">
              <template #default="scope">
                <span v-if="scope.row.expireTime">{{ scope.row.expireTime }}</span>
                <span v-else class="no-limit">永久有效</span>
              </template>
            </el-table-column>
          </el-table>
        </div>

        

        <!-- 已选优惠券信息 -->
        <div class="selected-coupons-info" v-if="selectedCoupons.length > 0">
          <h4>已选优惠券 ({{ selectedCoupons.length }}张)</h4>
          <div class="coupons-list">
            <div
              v-for="coupon in selectedCoupons"
              :key="coupon.id"
              class="coupon-item"
            >
              <div class="coupon-info">
                <el-tag
                  type="success"
                  closable
                  @close="removeSelectedCoupon(coupon)"
                  class="coupon-tag"
                >
                  {{ coupon.name }} - ¥{{ coupon.faceValue }}
                </el-tag>
              </div>
              <div class="coupon-quantity">
                <el-input
                  v-model="coupon.quantity"
                  type="number"
                  placeholder="数量"
                  style="width: 100px"
                  :min="1"
                  size="small"
                />
              </div>
            </div>
          </div>
        </div>
        
        <!-- 未选择优惠券时的提示 -->
        <div class="no-coupons-tip" v-else>
          <el-empty description="请从上方表格中选择要发送的优惠券">
            <template #image>
              <el-icon size="60" color="#ddd"><ShoppingCart /></el-icon>
            </template>
          </el-empty>
        </div>


      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="couponDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSendCoupon">确定发送</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 会员设置对话框 -->
    <el-dialog
      v-model="setMemberDialogVisible"
      title="设置会员"
      width="800px"
      :before-close="handleCloseSetMemberDialog"
    >
      <div class="member-set-container">
        <!-- 选中用户信息 -->
        <div class="selected-users-info">
          <h4>已选用户 ({{ selectedUsers.length }}人)</h4>
          <div class="users-list">
            <el-tag
              v-for="user in selectedUsers"
              :key="user.id"
              type="info"
              closable
              @close="removeSelectedUser(user)"
              class="user-tag"
            >
              {{ user.username }} - {{ user.realName || '未设置姓名' }}
            </el-tag>
          </div>
        </div>

        <!-- 会员等级选择 -->
        <div class="member-level-section">
          <h4>选择会员等级</h4>
          <el-form :model="memberForm" :rules="memberRules" ref="memberFormRef" label-width="120px">
            <el-form-item label="会员等级" prop="memberLevelId">
              <el-select v-model="memberForm.memberLevelId" placeholder="请选择会员等级" class="member-level-select">
                <el-option
                  v-for="level in memberLevelList"
                  :key="level.id"
                  :label="level.name"
                  :value="level.id"
                >
                  <div class="member-level-option">
                    <span class="level-name">{{ level.name }}</span>
                    <span class="level-desc">{{ level.description }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="会员有效期" prop="expireDate">
              <el-date-picker
                v-model="memberForm.expireDate"
                type="date"
                placeholder="选择会员到期时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                class="expire-date-picker"
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 当前会员信息显示 -->
        <div class="current-member-info" v-if="selectedUsers.length > 0">
          <h4>当前会员信息</h4>
          <div class="member-info-list">
            <div v-for="user in selectedUsers" :key="user.id" class="member-info-item">
              <div class="user-basic-info">
                <span class="user-name">{{ user.username }}</span>
                <span class="user-real-name">{{ user.realName || '未设置姓名' }}</span>
              </div>
              <div class="member-status">
                <el-tag v-if="user.memberInfo" type="success" size="small">
                  {{ user.memberInfo.levelName || '普通会员' }}
                </el-tag>
                <el-tag v-else type="info" size="small">非会员</el-tag>
              </div>
              <div class="member-expire" v-if="user.memberInfo">
                <span class="expire-label">到期时间：</span>
                <span class="expire-date">{{ user.memberInfo.expireDate || '永久' }}</span>
              </div>
              <!-- 调试信息 -->
              <div class="debug-info" style="font-size: 12px; color: #999; margin-top: 5px;">
                <div>用户ID: {{ user.id }}</div>
                <div>会员信息: {{ JSON.stringify(user.memberInfo) }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setMemberDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSetMember">确定设置</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { listUser, getUser, addUser, openMember, updateIntegral, getTagDictList, setUserTags, getUserTagsByUserId, updateUserTags, getUserShippingAddress, getUserMemberInfo, getMemberLevelList, setMember } from "@/api/user/user"
import { getCouponList, sendCouponToUsers, addUserCoupon } from "@/api/coupon/coupon"
import { listSource } from "@/api/source/source"
import { listRegion, listByParentCode } from "@/api/region/region"
import { ref, reactive, computed, onMounted, toRefs, getCurrentInstance } from "vue"
import { listMember } from "@/api/member/member"
import { 
  User
} from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()

// 表单验证规则
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  sourceId: [{ required: true, message: '请选择来源渠道', trigger: 'change' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }]
}

const userList = ref([])
const memberId = ref()
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const sourceList = ref([])
const provinceList = ref([])
const cityList = ref([])
const districtList = ref([])

// 获取来源渠道列表
const getSourceList = () => {
  listSource().then(response => {
    sourceList.value = response.data
  })
}

// 页面加载时获取来源渠道列表和省份列表
onMounted(() => {
  getSourceList()
  getProvinceList()
})

// 获取省份列表
function getProvinceList() {
  listRegion().then(response => {
    provinceList.value = response.data
  })
}

// 处理省份选择变化
function handleProvinceChange(value) {
  // 清空城市和区县列表
  cityList.value = []
  districtList.value = []
  form.value.cityId = null
  form.value.districtId = null

  if (value) {
    // 根据省份code获取城市列表
    listByParentCode(value).then(response => {
      cityList.value = response.data
    })
  }
}

// 处理城市选择变化
function handleCityChange(value) {
  // 清空区县列表
  districtList.value = []
  form.value.districtId = null

  if (value) {
    // 根据城市code获取区县列表
    listByParentCode(value).then(response => {
      districtList.value = response.data
    })
  }
}
const memberList = ref([])
const openMemberDialog = ref(false)
const openPointsDialog = ref(false)
const openTagDialog = ref(false)
const tagList = ref([])
const selectedTagIds = ref([])
const tagSearchValue = ref('')
const userTags = ref([])
const shippingAddress = ref([])
const dialogKey = ref(0)

// 优惠券相关
  const couponDialogVisible = ref(false)
  const couponList = ref([])
  const selectedCoupons = ref([])

// 会员设置相关
const setMemberDialogVisible = ref(false)
const selectedUsers = ref([])
const memberLevelList = ref([])
const memberForm = ref({
  memberLevelId: null,
  expireDate: null
})

const memberRules = {
  memberLevelId: [{ required: true, message: '请选择会员等级', trigger: 'change' }],
  expireDate: [{ required: true, message: '请选择会员到期时间', trigger: 'change' }]
}

const pointsForm = reactive({
  integral: '',
  modifyReason: ''
})

// 修改积分表单规则
const pointsRules = {
  integral: [
    { required: true, message: '请输入修改积分', trigger: 'blur' },
    { pattern: /^-?\d+$/, message: '请输入有效的数字', trigger: 'blur' }
  ],
  modifyReason: [
    { required: true, message: '请输入原因', trigger: 'blur' },
    { min: 1, max: 200, message: '原因长度在1-200个字符之间', trigger: 'blur' }
  ]
}

const data = reactive({
    form: {},
    searchType: '',
    searchValue: '',
         queryParams: {
       pageNum: 1, 
       pageSize: 10,
       accountNumber: null,
       username: null,
       phone: null,
       realName: null,
       memberNumber: null
     }
  })

const { queryParams, form, searchType, searchValue } = toRefs(data)

/** 查询用户列表 */
function getList() {
  loading.value = true
  listUser(queryParams.value).then(response => {
    userList.value = response.rows
    total.value = response.total
    loading.value = false
    console.log('用户列表加载完成，开始加载标签')
    
    // 先添加一些测试数据，验证显示功能
    if (userList.value.length > 0) {
      userList.value.forEach((user, index) => {
        const updatedUser = { 
          ...user, 
          userTags: [
            { tagId: 999, tagName: '测试显示' }
          ]
        }
        userList.value[index] = updatedUser
      })
      userList.value = [...userList.value]
      console.log('测试数据显示完成')
    }
    
    // 为每个用户加载标签信息
    loadUserTagsForList()
  })
}



  /** 获取会员列表 */
  function getMemberList() {
    listMember().then(response => {
      memberList.value = response.data
    })
  }
  getMemberList()

// 取消按钮
function cancel() {
  console.log('=== 关闭用户详情对话框 ===')
  console.log('清空前 - userTags:', userTags.value)
  console.log('清空前 - shippingAddress:', shippingAddress.value)
  console.log('清空前 - form:', form.value)
  
  // 关闭对话框
  open.value = false
  
  // 清空用户详情数据，避免数据混淆
  userTags.value = []
  shippingAddress.value = []
  form.value = {}
  
  // 更新dialogKey确保下次打开时重新渲染
  dialogKey.value++
  
  console.log('清空后 - userTags:', userTags.value)
  console.log('清空后 - shippingAddress:', shippingAddress.value)
  console.log('清空后 - form:', form.value)
  
  // 重置表单
  reset()
  
  console.log('=== 对话框关闭完成 ===')
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    accountNumber: null,
    username: null,
    realName: null,
    password: null,
    phone: null,
    photo: null,
    email: null,
    sex: null,
    age: null,
    birthTime: null,
    balance: null,
    sourceId: null,
    integral: null,
    memberId: null,
    createTime: null,
    provinceId: null,
    cityId: null,
    districtId: null,
    address: null
  }
  proxy.resetForm("userRef")
}

/** 搜索按钮操作 */
  function handleQuery() {
    // 重置所有搜索参数
    Object.keys(queryParams.value).forEach(key => {
      if (!['pageNum', 'pageSize'].includes(key)) {
        queryParams.value[key] = null;
      }
    });
    // 设置当前选择的搜索参数
    if (searchType.value && searchValue.value) {
      queryParams.value[searchType.value] = searchValue.value;
    }
    queryParams.value.pageNum = 1;
    getList();
  }

/** 重置按钮操作 */
  function resetQuery() {
    searchType.value = '';
    searchValue.value = '';
    proxy.resetForm("queryRef");
    // 重置所有搜索参数
    Object.keys(queryParams.value).forEach(key => {
      if (!['pageNum', 'pageSize'].includes(key)) {
        queryParams.value[key] = null;
      }
    });
    handleQuery();
  }

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
  selectedUsers.value = selection
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加用户"
}

/** 提交按钮 */
function submitForm() {
  addUser(form.value).then(response => {
    proxy.$modal.msgSuccess("新增成功")
    open.value = false
    getList()
  })
}

/** 详情按钮 */
function handleDetails(row) {
  console.log('=== 开始查看用户详情 ===')
  console.log('用户ID:', row.id)
  console.log('用户信息:', row)
  
  // 立即清空所有相关数据，确保没有残留
  userTags.value = []
  shippingAddress.value = []
  form.value = {}
  
  console.log('数据已清空 - userTags:', userTags.value)
  console.log('数据已清空 - shippingAddress:', shippingAddress.value)
  console.log('数据已清空 - form:', form.value)
  
  // 重置表单
  reset()
  
  // 更新dialogKey强制重新渲染
  dialogKey.value++
  
  // 打开对话框
  open.value = true
  title.value = "用户详情"
  
  console.log('对话框已打开，开始加载用户数据...')
  
  // 使用setTimeout确保DOM更新后再加载数据
  setTimeout(() => {
    // 获取用户基本信息
    getUser(row.id).then(response => {
      console.log('用户基本信息API响应:', response.data)
      form.value = response.data
      console.log('用户基本信息已设置:', form.value)
    }).catch(error => {
      console.error('获取用户基本信息失败:', error)
    })
    
    // 获取用户标签
    loadUserTags(row.id)
    
    // 获取用户收货地址
    loadUserShippingAddress(row.id)
    
    console.log('=== 用户详情加载完成 ===')
  }, 100)
}
getList()


/** 提交积分修改 */
function submitPointsForm() {
  const data = {
    idList: ids.value,
    integral: pointsForm.integral,
    modifyReason: pointsForm.modifyReason
  }
  console.log(data)
  // 这里可以添加调用API的逻辑
  updateIntegral(data).then(response => {
    proxy.$modal.msgSuccess('积分修改成功')
    openPointsDialog.value = false
  })
}

/** 提交会员等级 */
function submitMember() {
  if (!memberId) {
    proxy.$modal.msgWarning("请选择会员等级")
    return
  }
  const data = {
    memberId: memberId.value,
    idList: ids.value
  }
  openMember(data).then(response => {
    proxy.$modal.msgSuccess("会员开通成功")
    openMemberDialog.value = false
  })
}

/** 获取标签字典列表 */
function loadTagDictList() {
  return getTagDictList().then(response => {
    tagList.value = response.data || []
    return response.data || []
  })
}

/** 过滤标签 */
function filterTags() {
  if (!tagSearchValue.value) {
    return tagList.value
  }
  return tagList.value.filter(tag => 
    tag.tagName.toLowerCase().includes(tagSearchValue.value.toLowerCase())
  )
}

/** 计算过滤后的标签 */
const filteredTags = computed(() => {
  return filterTags()
})

/** 提交标签设置 */
function submitTags() {
  if (selectedTagIds.value.length === 0) {
    proxy.$modal.msgWarning("请至少选择一个标签")
    return
  }
  
  // 构建符合后端接口的数据格式
  const userTagDictDTOList = []
  
  // 为每个选中的用户创建标签关联
  ids.value.forEach(userId => {
    selectedTagIds.value.forEach(tagId => {
      userTagDictDTOList.push({
        id: userId,
        tagId: tagId
      })
    })
  })
  
  const data = {
    userTagDictDTOList: userTagDictDTOList
  }
  
  console.log('提交标签数据:', data)
  
  updateUserTags(data).then(response => {
    proxy.$modal.msgSuccess("标签设置成功")
    openTagDialog.value = false
    selectedTagIds.value = []
    getList()
  }).catch((error) => {
    console.error('标签设置失败:', error)
    proxy.$modal.msgError("标签设置失败")
  })
}

/** 打开标签对话框 */
function handleOpenTagDialog() {
  selectedTagIds.value = []
  tagSearchValue.value = ''
  openTagDialog.value = true
  
  // 先加载标签列表，然后设置预选
  loadTagDictList().then(() => {
    // 如果只选择了一个用户，加载该用户的现有标签并预选
    if (ids.value.length === 1) {
      const userId = ids.value[0]
      console.log(`加载用户 ${userId} 的现有标签用于预选`)
      getUserTagsByUserId(userId)
        .then(response => {
          // 将现有标签的ID添加到选中列表中
          const existingTagIds = (response.data || []).map(tag => tag.tagId)
          selectedTagIds.value = existingTagIds
          console.log(`用户 ${userId} 的现有标签已预选:`, existingTagIds)
        })
        .catch(error => {
          console.error(`加载用户 ${userId} 现有标签失败:`, error)
          selectedTagIds.value = []
        })
    } else if (ids.value.length > 1) {
      // 如果选择了多个用户，不预选任何标签
      console.log('多用户选择，不预选标签')
    }
  })
}

/** 根据用户ID获取用户标签 */
function loadUserTags(userId) {
  getUserTagsByUserId(userId).then(response => {
    userTags.value = response.data || []
  }).catch(() => {
    userTags.value = []
  })
}

/** 根据用户ID获取用户收货地址 */
function loadUserShippingAddress(userId) {
  console.log('=== 开始加载用户收货地址 ===')
  console.log('用户ID:', userId)
  console.log('当前shippingAddress状态:', shippingAddress.value)
  
  if (!userId) {
    console.error('用户ID为空，无法加载收货地址')
    shippingAddress.value = []
    return
  }
  
  getUserShippingAddress(userId).then(response => {
    console.log('收货地址API响应:', response)
    console.log('收货地址API响应数据:', response.data)
    
    // API返回的是数组，处理所有地址
    const addressList = response.data || []
    console.log('原始地址列表:', addressList)
    
    if (addressList.length > 0) {
      // 映射所有地址的字段名，将省市区分开显示
      const processedAddresses = addressList.map((address, index) => {
        const processedAddress = {
          recipient: address.contacts || '',
          recipientPhone: address.phone || '',
          provinceName: address.provinceName || '',
          cityName: address.cityName || '',
          districtName: address.districtName || '',
          detailAddress: address.detailAddress || address.address || '', // 优先使用detailAddress字段
          isDefault: address.isDefault || false // 是否为默认地址
        }
        console.log(`处理第${index + 1}个地址:`, processedAddress)
        return processedAddress
      })
      
      // 强制响应式更新
      shippingAddress.value = []
      setTimeout(() => {
        shippingAddress.value = processedAddresses
        console.log('最终设置的收货地址数据:', shippingAddress.value)
      }, 0)
    } else {
      shippingAddress.value = []
      console.log('用户没有收货地址，已清空shippingAddress')
    }
  }).catch((error) => {
    console.error('加载用户收货地址失败:', error)
    console.error('错误详情:', error.response || error.message)
    shippingAddress.value = []
  })
}

/** 为列表中的用户加载标签信息 */
function loadUserTagsForList() {
  if (!userList.value || userList.value.length === 0) {
    return
  }
  
  console.log('开始加载用户标签，用户数量:', userList.value.length)
  
  // 逐个加载用户标签，确保响应式更新
  userList.value.forEach((user, index) => {
    console.log(`加载第${index + 1}个用户的标签，用户ID:`, user.id)
    
    getUserTagsByUserId(user.id)
      .then(response => {
        console.log(`用户${user.id}的标签数据:`, response.data)
        // 使用Vue的响应式更新 - 创建新对象
        const updatedUser = { ...user, userTags: response.data || [] }
        userList.value[index] = updatedUser
        // 强制触发响应式更新
        userList.value = [...userList.value]
        console.log(`用户${user.id}标签更新完成:`, updatedUser.userTags)
      })
      .catch(error => {
        console.error(`加载用户${user.id}的标签失败:`, error)
        // 使用Vue的响应式更新 - 创建新对象
        const updatedUser = { ...user, userTags: [] }
        userList.value[index] = updatedUser
        // 强制触发响应式更新
        userList.value = [...userList.value]
      })
  })
}

// 会员设置相关函数
function openSetMemberDialog() {
  if (selectedUsers.value.length === 0) {
    proxy.$modal.msgWarning('请先选择用户')
    return
  }
  
  setMemberDialogVisible.value = true
  loadMemberLevelList()
  loadSelectedUsersMemberInfo()
}

function loadMemberLevelList() {
  getMemberLevelList().then(response => {
    memberLevelList.value = response.data || []
  }).catch(error => {
    console.error('获取会员等级列表失败:', error)
    memberLevelList.value = []
  })
}

function loadSelectedUsersMemberInfo() {
  console.log('=== 开始加载选中用户的会员信息 ===')
  console.log('选中的用户数量:', selectedUsers.value.length)
  console.log('选中的用户:', selectedUsers.value)
  
  // 为选中的用户加载会员信息
  selectedUsers.value.forEach((user, index) => {
    console.log(`正在加载用户 ${user.id} (${user.username}) 的会员信息...`)
    if (user.id) {
      getUserMemberInfo(user.id).then(response => {
        console.log(`用户 ${user.id} 的会员信息API响应:`, response)
        user.memberInfo = response.data || null
        console.log(`用户 ${user.id} 的会员信息已设置:`, user.memberInfo)
        
        // 强制更新视图
        selectedUsers.value[index] = { ...user }
        selectedUsers.value = [...selectedUsers.value]
      }).catch(error => {
        console.error(`获取用户 ${user.id} 会员信息失败:`, error)
        user.memberInfo = null
        // 强制更新视图
        selectedUsers.value[index] = { ...user }
        selectedUsers.value = [...selectedUsers.value]
      })
    }
  })
}

function removeSelectedUser(user) {
  const index = selectedUsers.value.findIndex(u => u.id === user.id)
  if (index > -1) {
    selectedUsers.value.splice(index, 1)
    ids.value = selectedUsers.value.map(u => u.id)
    multiple.value = !selectedUsers.value.length
  }
}

function submitSetMember() {
  if (selectedUsers.value.length === 0) {
    proxy.$modal.msgWarning('请先选择用户')
    return
  }
  
  if (!memberForm.value.memberLevelId) {
    proxy.$modal.msgWarning('请选择会员等级')
    return
  }
  
  if (!memberForm.value.expireDate) {
    proxy.$modal.msgWarning('请选择会员到期时间')
    return
  }
  
  // 构建设置会员的数据
  const memberData = selectedUsers.value.map(user => ({
    userId: user.id,
    memberId: memberForm.value.memberLevelId
  }))
  
  // 调用设置会员接口
  setMember(memberData).then(response => {
    proxy.$modal.msgSuccess('会员设置成功')
    setMemberDialogVisible.value = false
    // 重新加载用户列表
    getList()
  }).catch(error => {
    console.error('设置会员失败:', error)
    proxy.$modal.msgError('设置会员失败')
  })
}

// 优惠券相关函数
function handleSendCoupon() {
  if (selectedUsers.value.length === 0) {
    proxy.$modal.msgWarning('请先选择用户')
    return
  }
  
  couponDialogVisible.value = true
  loadCouponList()
}

function loadCouponList() {
  getCouponList().then(response => {
    couponList.value = response.data || []
    console.log('优惠券列表加载完成:', couponList.value)
  }).catch(error => {
    console.error('获取优惠券列表失败:', error)
    proxy.$modal.msgError('获取优惠券列表失败')
    couponList.value = []
  })
}

function handleCouponSelectionChange(selection) {
  // 为每个选中的优惠券添加quantity字段
  selectedCoupons.value = selection.map(coupon => ({
    ...coupon,
    quantity: coupon.quantity || 1
  }))
  console.log('已选优惠券:', selectedCoupons.value)
}

function removeSelectedCoupon(coupon) {
  const index = selectedCoupons.value.findIndex(c => c.id === coupon.id)
  if (index > -1) {
    selectedCoupons.value.splice(index, 1)
  }
}

function submitSendCoupon() {
  if (selectedUsers.value.length === 0) {
    proxy.$modal.msgWarning('请先选择用户')
    return
  }
  
  if (selectedCoupons.value.length === 0) {
    proxy.$modal.msgWarning('请先选择优惠券')
    return
  }
  
  // 按照您图中的API格式构建数据
  const couponData = []
  
  // 为每个用户和每个优惠券创建一条记录
  selectedUsers.value.forEach(user => {
    selectedCoupons.value.forEach(coupon => {
      couponData.push({
        userId: user.id,
        couponTemplateId: coupon.id,
        couponNum: coupon.quantity || 1
      })
    })
  })
  
  console.log('发送优惠券数据:', couponData)
  
  // 调用新的API接口
  addUserCoupon(couponData).then(response => {
    proxy.$modal.msgSuccess('优惠券发送成功')
    couponDialogVisible.value = false
    // 重新加载用户列表
    getList()
  }).catch(error => {
    console.error('发送优惠券失败:', error)
    proxy.$modal.msgError('发送优惠券失败')
  })
}

  function handleCloseCouponDialog() {
    couponDialogVisible.value = false
    selectedCoupons.value = []
    couponList.value = []
  }

function handleCloseSetMemberDialog() {
  setMemberDialogVisible.value = false
  selectedUsers.value = []
  memberForm.value = {
    memberLevelId: null,
    expireDate: null
  }
}

</script>

<style scoped>
/* 页面整体布局 */
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 页面标题区域 */
.page-header {
  margin-bottom: 24px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.page-subtitle {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

/* 操作按钮区域 */
.action-section {
  margin-bottom: 20px;
}

.action-btn {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 搜索区域 */
.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.search-select {
  width: 180px;
}

.search-input {
  width: 220px;
}

.search-btn, .reset-btn {
  border-radius: 6px;
  font-weight: 500;
}

/* 批量操作区域 */
.batch-section {
  margin-bottom: 20px;
}

.batch-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.batch-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.batch-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-right: 12px;
}

.batch-tip {
  font-size: 12px;
  color: #909399;
}

.batch-buttons {
  margin-top: 16px;
}

.batch-btn {
  width: 100%;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.batch-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 表格区域 */
.table-section {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.user-table {
  border-radius: 8px;
  overflow: hidden;
}

.user-table :deep(.el-table__header) {
  background-color: #f8f9fa;
}

.user-table :deep(.el-table__header th) {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
  border-bottom: 2px solid #e4e7ed;
}

.user-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 用户信息容器 */
.user-info-container {
  display: flex;
  align-items: center;
  padding: 8px 0;
  gap: 12px;
}

.user-avatar {
  flex-shrink: 0;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  line-height: 1.2;
}

.user-phone {
  font-size: 12px;
  color: #909399;
  line-height: 1.2;
}

/* 用户标签样式 */
.user-tags-list {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 6px;
  min-height: 24px;
  padding: 4px 0;
}

.user-tag {
  border-radius: 12px;
  font-size: 11px;
  padding: 2px 8px;
  border: none;
  background-color: #e1f3ff;
  color: #1890ff;
}

.no-tags {
  color: #c0c4cc;
  font-size: 12px;
  font-style: italic;
}

/* 操作按钮 */
.action-link {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.action-link:hover {
  transform: translateY(-1px);
}

/* 分页容器 */
.pagination-container {
  padding: 20px;
  display: flex;
  justify-content: center;
  background-color: #fafafa;
  border-top: 1px solid #e4e7ed;
}

/* 对话框样式 */
.user-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

.user-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 24px;
}

.user-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

.user-dialog :deep(.el-dialog__body) {
  padding: 24px;
  max-height: 70vh;
  overflow-y: auto;
}

/* 表单区域样式 */
.form-section {
  margin-bottom: 32px;
  padding: 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e4e7ed;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.section-title .el-icon {
  color: #667eea;
  font-size: 18px;
}

/* 头像上传容器 */
.avatar-upload-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.upload-tips {
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  border: 1px solid #91d5ff;
  border-radius: 8px;
  padding: 16px;
  margin-top: 12px;
}

.upload-tips p {
  margin: 0 0 8px 0;
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
}

.upload-tips p:last-child {
  margin-bottom: 0;
}

.upload-tips .highlight {
  color: #1890ff;
  font-weight: 500;
}

/* 性别选择组 */
.gender-group {
  display: flex;
  gap: 24px;
}

.gender-radio {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  background-color: white;
  transition: all 0.3s ease;
}

.gender-radio:hover {
  border-color: #1890ff;
  background-color: #f0f9ff;
}

.gender-radio .el-icon {
  font-size: 14px;
  color: #909399;
}

.gender-radio.is-checked {
  border-color: #1890ff;
  background-color: #e6f7ff;
  color: #1890ff;
}

.gender-radio.is-checked .el-icon {
  color: #1890ff;
}

/* 表单标签容器优化 */
.user-tags-container {
  min-height: 50px;
  padding: 16px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  background-color: #fafafa;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  transition: all 0.3s ease;
}

.user-tags-container:hover {
  border-color: #1890ff;
  background-color: #f0f9ff;
}

.form-tag {
  border-radius: 12px;
  font-size: 12px;
  padding: 6px 12px;
  border: none;
  background-color: #e1f3ff;
  color: #1890ff;
  transition: all 0.3s ease;
}

.form-tag:hover {
  background-color: #bae7ff;
  transform: translateY(-1px);
}

/* 必填字段标识 */
.el-form-item.is-required .el-form-item__label::before {
  color: #f56c6c;
  font-weight: bold;
}

/* 表单输入框优化 */
.user-dialog :deep(.el-input__wrapper) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.user-dialog :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #1890ff;
}

.user-dialog :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #1890ff;
}

/* 下拉选择框优化 */
.user-dialog :deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
}

/* 日期选择器优化 */
.user-dialog :deep(.el-date-editor) {
  border-radius: 8px;
}

/* 文本域优化 */
.user-dialog :deep(.el-textarea__inner) {
  border-radius: 8px;
  resize: vertical;
}

/* 对话框滚动条 */
.user-dialog :deep(.el-dialog__body)::-webkit-scrollbar {
  width: 6px;
}

.user-dialog :deep(.el-dialog__body)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.user-dialog :deep(.el-dialog__body)::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.user-dialog :deep(.el-dialog__body)::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 其他对话框样式 */
.member-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

.member-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
  color: white;
  padding: 20px 24px;
}

.member-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

.tag-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

.tag-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  color: white;
  padding: 20px 24px;
}

.tag-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

.points-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

.points-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #fa8c16 0%, #d46b08 100%);
  color: white;
  padding: 20px 24px;
}

.points-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

/* 标签搜索容器 */
.tag-search-container {
  margin-bottom: 20px;
}

.tag-search-input {
  border-radius: 8px;
}

.tag-list-container {
  max-height: 300px;
  overflow-y: auto;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fafafa;
  margin-bottom: 16px;
}

.tag-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.tag-checkbox {
  padding: 8px 12px;
  border-radius: 6px;
  background-color: white;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.tag-checkbox:hover {
  background-color: #f0f9ff;
  border-color: #1890ff;
}

.selected-tags-info {
  color: #606266;
  font-size: 14px;
  text-align: center;
  padding: 12px;
  background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
  border-radius: 8px;
  border: 1px solid #91d5ff;
  margin-top: 16px;
}

/* 表单提示 */
.form-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

/* 对话框底部 */
.dialog-footer {
  padding: 16px 24px;
  background-color: #fafafa;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 12px;
  }
  
  .page-header {
    padding: 16px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .batch-buttons .el-col {
    margin-bottom: 12px;
  }
  
  .user-table {
    font-size: 12px;
  }
  
  .user-info-container {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
  
  .form-section {
    padding: 16px;
  }
  
  .gender-group {
    flex-direction: column;
    gap: 12px;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.app-container {
  animation: fadeIn 0.5s ease-out;
}

/* 加载状态 */
.loading-overlay {
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
}

/* 收货地址容器 */
.shipping-address-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.address-item {
  padding: 20px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-radius: 12px;
  border: 1px solid #bae7ff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.address-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.address-header {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #d6e4ff;
}

.address-title {
  font-size: 16px;
  font-weight: 600;
  color: #1890ff;
  display: flex;
  align-items: center;
  gap: 8px;
}

.address-title::before {
  content: '';
  width: 4px;
  height: 16px;
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  border-radius: 2px;
}

.default-tag {
  margin-left: 8px;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
  color: white;
  border: none;
}

.no-address-container {
  padding: 40px 20px;
  text-align: center;
  background: linear-gradient(135deg, #fafafa 0%, #f5f5f5 100%);
  border-radius: 8px;
  border: 1px dashed #d9d9d9;
}

.no-address-container :deep(.el-empty__description) {
  color: #909399;
  font-size: 14px;
}

/* 滚动条样式 */
.tag-list-container::-webkit-scrollbar {
  width: 6px;
}

.tag-list-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.tag-list-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.tag-list-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 会员设置对话框样式 */
.member-set-container {
  padding: 20px;
}

.selected-users-info {
  margin-bottom: 24px;
  padding: 16px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-radius: 8px;
  border: 1px solid #bae7ff;
}

.selected-users-info h4 {
  margin: 0 0 12px 0;
  color: #1890ff;
  font-size: 16px;
  font-weight: 600;
}

.users-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.user-tag {
  margin: 0;
  border-radius: 6px;
  font-size: 12px;
}

.member-level-section {
  margin-bottom: 24px;
  padding: 16px;
  background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
  border-radius: 8px;
  border: 1px solid #b7eb8f;
}

.member-level-section h4 {
  margin: 0 0 16px 0;
  color: #52c41a;
  font-size: 16px;
  font-weight: 600;
}

.member-level-select {
  width: 100%;
}

.member-level-option {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.level-name {
  font-weight: 600;
  color: #1890ff;
}

.level-desc {
  font-size: 12px;
  color: #666;
}

.expire-date-picker {
  width: 100%;
}

.current-member-info {
  padding: 16px;
  background: linear-gradient(135deg, #fff7e6 0%, #ffe7ba 100%);
  border-radius: 8px;
  border: 1px solid #ffd591;
}

.current-member-info h4 {
  margin: 0 0 16px 0;
  color: #fa8c16;
  font-size: 16px;
  font-weight: 600;
}

.member-info-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.member-info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  background: white;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.user-basic-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  font-weight: 600;
  color: #333;
}

.user-real-name {
  font-size: 12px;
  color: #666;
}

.member-status {
  margin: 0 16px;
}

.member-expire {
  font-size: 12px;
  color: #666;
}

.expire-label {
  color: #999;
}

.expire-date {
  color: #1890ff;
  font-weight: 500;
}

/* 优惠券对话框样式 */
.coupon-container {
  padding: 20px;
}

.coupon-list-section {
  margin: 24px 0;
  padding: 16px;
  background: linear-gradient(135deg, #fff7e6 0%, #ffe7ba 100%);
  border-radius: 8px;
  border: 1px solid #ffd591;
}

.coupon-list-section h4 {
  margin: 0 0 8px 0;
  color: #fa8c16;
  font-size: 16px;
  font-weight: 600;
}

.coupon-tip {
  margin: 0 0 16px 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.no-limit {
  color: #52c41a;
  font-style: italic;
}

.selected-coupons-info {
  margin-top: 24px;
  padding: 16px;
  background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
  border-radius: 8px;
  border: 1px solid #b7eb8f;
}

.selected-coupons-info h4 {
  margin: 0 0 12px 0;
  color: #52c41a;
  font-size: 16px;
  font-weight: 600;
}

.coupons-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.coupon-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.coupon-info {
  flex: 1;
}

.coupon-quantity {
  margin-left: 16px;
}

.no-coupons-tip {
  margin-top: 24px;
  padding: 40px 20px;
  text-align: center;
  background: #fafafa;
  border-radius: 8px;
  border: 1px dashed #d9d9d9;
}

.coupon-tag {
  margin: 0;
  border-radius: 6px;
  font-size: 12px;
  background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
  color: white;
  border: none;
}

.coupon-tag:hover {
  background: linear-gradient(135deg, #389e0d 0%, #237804 100%);
  transform: translateY(-1px);
}




</style>

